package com.hz.config;

import com.hz.utils.AjaxAuthenticationEntryPoint;
import com.hz.utils.AjaxLogoutSuccessHandler;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;

import javax.annotation.Resource;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    /**
     *  未登陆时返回 JSON 格式的数据给前端
     */
    @Resource
    AjaxAuthenticationEntryPoint ajaxAuthenticationEntryPoint;

    /**
     * 注销成功返回的 JSON 格式数据给前端
     */
    @Resource
    AjaxLogoutSuccessHandler ajaxLogoutSuccessHandler;


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 去掉 CSRF
        http.csrf().disable()
                //返回false走这里
                .exceptionHandling().authenticationEntryPoint(ajaxAuthenticationEntryPoint)
                .and()
                // 基于Token 不需要Session
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                // 登录处理
                .and()
                .formLogin()
                .loginProcessingUrl("admin/login")
                .permitAll()

                //  登录和权限控制
                .and()
                .authorizeRequests()
                .anyRequest()
                // RBAC 动态 url 认证
                .access("@rbacauthorityservice.hasPermission(request,authentication)")

                //注销处理
                .and()
                .logout()//默认注销行为为logout
                .logoutUrl("/admin/loginOut")
                .logoutSuccessHandler(ajaxLogoutSuccessHandler)
                .permitAll();

    }

}
